<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from "vue";
import {
    UploadOutlined,
    RightOutlined
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
import { useRouter, useRoute } from "vue-router";

import baseModel from "@/components/baseModel/baseModel.vue";
import { nextTick } from "vue";

const emit = defineEmits(['clearId'])

const props = defineProps({
    id: {
        type: Number || String,
        default: () => {
            return ''
        }
    }
})

const route = useRoute();
const router = useRouter();
const formRef = ref(null)

const formState = reactive({
    platform_name: '',// 项目名称
    link_name: '', // 链接标题
    link_des: '', // 介绍语
    status: 1, // 状态, 开启或关闭
    to_image: '', // 微信二维码
    link_image: '' // 链接图片
})

// 路由参数
const query = computed(() => {
    return {
        id: route.query?.id || props.id
    }
})

onMounted(() => {
    if (query.value.id) {
        getDetail()
    }
})

// 图片预览实例组件
const dialog = ref(null)
const imgUrl = ref('')
const handlePreview = (file) => {
    if (file.status == 'done' && file?.response?.data?.fileUrl) {
        imgUrl.value = file?.response?.data?.fileUrl
        nextTick(() => {
            dialog.value.showModal()
        })
    }
}

const getDetail = async () => {
    const res = await request.get('work_ai', '/user/shotstack/toReachCustomers/detail', {
        id: query.value.id
    })
    console.log(res, '查看详情');
    for (let key in formState) {
        formState[key] = res.result[key]
    }
    // 初始赋值
    linkFileList.value.push({
        uid: res.result.link_image,
        status: 'done',
        response: {
            data: {
                fileName: res.result?.link_image_file_name || '素材',
                fileUrl: res.result.link_image
            }
        },
        name: res.result?.link_image_file_name || '素材'
    })
    QRFileList.value.push({
        uid: res.result.to_image,
        status: 'done',
        response: {
            data: {
                fileName: res.result.to_image_file_name || '素材',
                fileUrl: res.result.to_image
            }
        },
        name: res.result.to_image_file_name || '素材'
    })
}

const linkFileList = ref([])
const QRFileList = ref([])
const handleChange = (info, type) => {
    console.log(info, '上传中...');
    if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        console.log(info, 'info');
        console.log(linkFileList.value, '文件对象');
        if (type == 'link') {
            formState.link_image = info.file.response.data.fileUrl;
        } else {
            formState.to_image = info.file.response.data.fileUrl;
        }
    } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
    }
}
// 图片的校验规则
const QRFileListValid = async () => {
    if (!QRFileList.value.length) {
        // if (!formState.to_image) {
        return Promise.reject('请上传微信好友二维码!')
    } else {
        return Promise.resolve();
    }
}
const linkFileListValid = async () => {
    if (!linkFileList.value.length) {
        return Promise.reject('请上传链接图片!')
    } else {
        return Promise.resolve();
    }
}

// 删除已上传列表中的某项
const delImg = (type, file, fileList) => {
    console.log(file, fileList, '删除某项');
    if (type == 'linkFileList') {
        const index = linkFileList.value.findIndex(ele => ele.uid == file.uid)
        index != -1 && linkFileList.value.splice(index, 1);
        formState.link_image = ''
        return
    }
    const index = QRFileList.value.findIndex(ele => ele.uid == file.uid)
    index != -1 && QRFileList.value.splice(index, 1);
    formState.to_image = ''

}

const btn_loding = ref(false);

const back = () => {
    router.push({
        name: 'TiktoktoWechat',
        query: {
            type: 'link'
        }
    })
}

// 抖转微创建提交
const submit = async () => {
    console.log(formState, '提交的数据');
    // return
    try {
        // 判断是新增还是修改
        const sendType = query.value.id ? {
            url: '/user/shotstack/toReachCustomers/update',
            type: 'put',
            msg: '修改成功!'
        } : {
            url: '/user/shotstack/toReachCustomers/add',
            type: 'post',
            msg: '创建成功!'
        }
        Promise.all([formRef.value.validateFields()]).then(async () => {
            if (linkFileList.value[0].status != 'done' || QRFileList.value[0].status != 'done') {
                return message.warn('图片正在上传中, 请稍后再试!')
            }
            btn_loding.value = true

            const res = await request[sendType.type]('work_ai', sendType.url, {
                ...formState,
                id: query.value?.id || undefined
            })
            console.log(res, '创建结果');
            message.success(sendType.msg);
            setTimeout(() => {
                back()
            }, 500)
        })
    } catch (error) {

    } finally {
        btn_loding.value = false
    }

}

onUnmounted(() => {
    emit('clearId')
})
</script>

<template>
    <a-alert message="本平台积极配合警方反诈工作！应公安部要求，我们将对生成的内容进行检测，如发现违反法律法规（包括但不限于诈骗，色情，贷款，博彩，赌球等）,则立即封禁相关账号，且不予退款。" banner
        closable style=' width:111.7%; margin-top:-10px; margin-bottom: 10px; margin-left:-15px; ' />
    <div class="Creatingdrainagetool">
        <!-- 头部 -->
        <div class="header_box">
            <a-button @click="back">返回</a-button>
        </div>

        <div class="all_contnet">
            <!-- 表单区域 -->
            <div class="from_content">
                <a-form ref="formRef" style="width: 100%;" :model="formState" :label-col="{ style: { width: '150px' } }"
                    :wrapper-col="{ span: 14 }">
                    <a-form-item label="外链名称" name="platform_name"
                        :rules="[{ required: true, message: '请输入外链名称!', trigger: 'change' }]">
                        <a-input :maxlength="60" placeholder="请输入外链名称" v-model:value="formState.platform_name"
                            allowClear />
                    </a-form-item>
                    <a-form-item name="link_name" label="链接标题"
                        :rules="[{ required: true, message: '请输入链接标题!', trigger: 'change' }]">
                        <a-input :maxlength="60" v-model:value="formState.link_name" placeholder="请输入链接标题" allowClear />
                    </a-form-item>
                    <a-form-item label="链接图片" name="linkFileList"
                        :rules="[{ required: true, validator: linkFileListValid, message: '请上传链接图片!', trigger: 'change' }]">
                        <a-upload v-model:file-list="linkFileList" :maxCount="1" :action="$utils.sendImg"
                            :headers="{ 'org-token': $store.getters.token }" @change="handleChange($event, 'link')"
                            :multiple="false" name="image" :data="{ dir: 'work_ai' }" accept=".png,.gif,.jpeg,.jpg">
                            <a-button>
                                <upload-outlined></upload-outlined>
                                上传文件
                            </a-button>
                            <template #itemRender="{ file, fileList }">
                                <div class="img_box" @click="handlePreview(file)">
                                    <a-spin tip="上传中..." size="small" v-if="file.status === 'uploading'" />
                                    <img :src="file?.response?.data?.fileUrl" alt="" v-else />
                                    <a-popconfirm title="确定删除此项吗?" ok-text="确定" cancel-text="取消"
                                        @confirm="delImg('linkFileList', file, fileList)">
                                        <a-button @click.stop="() => { }" class="btn" type="link"
                                            v-show="file.status === 'done'">删除</a-button>
                                    </a-popconfirm>
                                </div>
                            </template>
                        </a-upload>
                    </a-form-item>
                    <a-form-item label="介绍语" name="link_des">
                        <a-input :maxlength="200" placeholder="请输入介绍语" v-model:value="formState.link_des" allowClear />
                    </a-form-item>
                    <a-form-item label="微信好友二维码" name="QRFileList"
                        :rules="[{ required: true, validator: QRFileListValid, message: '请上传好友二维码!', trigger: 'change' }]">
                        <a-upload list-type="picture" v-model:file-list="QRFileList" :action="$utils.sendImg"
                            :maxCount="1" :headers="{ 'org-token': $store.getters.token }"
                            @change="handleChange($event, 'QRcode')" :multiple="false" name="image"
                            :data="{ dir: 'work_ai' }" accept=".png,.gif,.jpeg,.jpg">
                            <a-button>
                                <upload-outlined></upload-outlined>
                                上传文件
                            </a-button>
                            <template #itemRender="{ file, fileList }">
                                <div class="img_box" @click="handlePreview(file)">
                                    <a-spin tip="上传中..." size="small" v-if="file.status === 'uploading'" />
                                    <img :src="file?.response?.data?.fileUrl" alt="" v-else />
                                    <a-popconfirm title="确定删除此项吗?" ok-text="确定" cancel-text="取消"
                                        @confirm="delImg('QRFileList', file, fileList)">
                                        <a-button @click.stop="() => { }" class="btn" type="link"
                                            v-show="file.status === 'done'">删除</a-button>
                                    </a-popconfirm>
                                </div>
                            </template>
                        </a-upload>
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-switch v-model:checked="formState.status" :checkedValue="1" :unCheckedValue="2" />
                    </a-form-item>
                </a-form>
                <a-button type="primary" class="btn" :loading="btn_loding" style="width: 120px" @click="submit"> {{
                    query?.id ? '修改' : '创建' }}
                </a-button>
            </div>

            <div class="right_content">
                <img src="./imgs/toview.png" alt="">
                <!-- <div class="img_items">
                    <div class="toView_content">
                        <img style="" src="./imgs/weiContent.jpg" alt="">
                    </div>
                    <RightOutlined style="margin: 0 15px; font-weight: 900; color: var(--ss-primary-color);">
                    </RightOutlined>
                    <img src="./imgs/table.png" alt="">
                </div> -->

            </div>
        </div>
        <baseModel ref="dialog" :contentWidth="'500px'" :zIndex="1011" :maskClosable="true" :centered="false"
            :closable="true">
            <template #title>
                <div class="title_box">
                    <span class="title">LOGO预览</span>
                </div>
            </template>
            <template #content>
                <div style="width: 100%; height: 500px; display: flex; justify-content: center;">
                    <img :src="imgUrl" alt="" style="height: 100%; width: 100%; object-fit: contain; " />
                </div>
            </template>
            <template #footer>
                <a-button type="primary" @click="dialog.closeModal()">确定</a-button>
            </template>
        </baseModel>
    </div>

</template>

<style lang="less" scoped>
.Creatingdrainagetool {
    padding: 14px;
    width: 100%;
    overflow-x: scroll ;
    &::-webkit-scrollbar {
        display: none;
    }

    .all_contnet {

        display: flex;

        gap: 20px;

        .right_content {
            flex: 1;
            min-width: 100px;
            img{
                width: 100%;
            }
            .img_items {}
        }

        .from_content {
            width: 55%;
            min-width: 100px;

            .btn {
                margin-left: 100px;
                margin-top: 20px;
            }

            .img_box {
                cursor: pointer;
                margin-top: 10px;
                padding: 5px;
                border: 1px solid #dde2e9;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .btn {
                    padding: 0;
                    margin: 0;
                }

                img {
                    width: 40px;
                    height: 40px;
                    object-fit: cover;
                }
            }
        }
    }

    .header_box {
        display: flex;
        height: 32px;
        line-height: 32px;
        margin-bottom: 20px;

        button {
            border-radius: 5px;
            margin-right: 5px
        }
    }
}
</style>